import { writeFileSync } from 'fs';
import { join } from 'path';
import { IMessage } from 'qq-guild-bot';
import { stringify } from 'yaml';
import { readYaml } from '../../../src/lib/tool';

export async function del(e: { eventType: string; msg: IMessage }) {
  // 私聊禁用
  if (e.eventType === 'DIRECT_MESSAGE_CREATE') {
    return;
  }

  // 1	全体成员
  // 2	管理员
  // 4	群主/创建者
  // 5	子频道管理员
  // 没有权限
  if (
    !e.msg.member.roles.includes('4')
    // && !e.msg.member.roles.includes('5')
  ) {
    let message = {
      content: `<@!${e.msg.author.id}> 无权限`,
      msg_id: e.msg.id
    };
    await client.messageApi.postMessage(e.msg.channel_id, message);

    return true;
  }

  let msg = e.msg.content.replace('/删除', '').replace(`<@!${bot.id}>`, '').trim();
  if (msg === '') {
    let message = {
      content: `<@!${e.msg.author.id}> 内容不能为空!`,
      msg_id: e.msg.id
    };
    await client.messageApi.postMessage(e.msg.channel_id, message);
    return true;
  }

  let bqPath = join(process.cwd(), '/plugins/biaoqing/resources/biaoqing/biaoqing.yaml');

  let bq = readYaml(bqPath);

  if ((bq ?? '') === '' || typeof bq === 'string' || Object.keys(bq).length === 0) {
    return;
  }
  let newList = {};

  let list = Object.keys(bq);
  for (let item of list) {
    if (msg !== item) {
      newList[item] = bq[item];
    }
  }

  writeFileSync(bqPath, stringify(newList));

  let message = {
    content: `<@!${e.msg.author.id}> 删除成功!`,
    msg_id: e.msg.id
  };
  await client.messageApi.postMessage(e.msg.channel_id, message);
  return true;
}
